//
//  InputCodeVC.swift
//  BaseSwift
//
//  Created by gh on 2019/10/8.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class InputCodeVC: UIViewController {

    var phone:String?
    let intro1Lab = UILabel()
    var type:String?

    let codeV: CodeView = CodeView()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.navigationView.setTitle("")
        self.view.backgroundColor = UIColor.white
        
        let bgimg = UIImageView()
        bgimg.isUserInteractionEnabled = true
        let ges = UITapGestureRecognizer(target: self, action: #selector(bgClick))
        ges.numberOfTouchesRequired = 1
        ges.numberOfTapsRequired = 1
        bgimg.addGestureRecognizer(ges)
        view.addSubview(bgimg)
        let _ = bgimg.sd_layout()?.spaceToSuperView(.zero)
        
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "输入验证码")
        label.frame = CGRect(x: 32, y: HT_StatusBarAndNavigationBarHeight+24, width: 300, height: 30)
        label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 30),.foregroundColor: UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        view.addSubview(label)
        
        let introLab = UILabel()
        introLab.text = String(format: "验证码已发送至%@", self.phone!)
        introLab.textColor = UIColor.textTitleColor
        introLab.font = UIFont.commonFontSmaller
        view.addSubview(introLab)
        let _ = introLab.sd_layout()?.leftSpaceToView(view,32)!.heightIs(20)!.topSpaceToView(label,16)!.rightSpaceToView(view,32)
        introLab.updateLayout()
        
        codeV.frame = CGRect(x: 32, y: introLab.frame.maxY+20, width: self.view.frame.size.width - 32*2, height: 35)
        codeV.Base.changeInputNum(num: 4)
        codeV.Base.lineColor = UIColor.lineColor
        codeV.Base.lineInputColor = UIColor.GP_Orange_Color
        codeV.Base.fontNum = UIFont.systemFont(ofSize: 30, weight: UIFont.Weight(rawValue: 0.2))
        codeV.Base.errorlineViewColor = UIColor.GP_Red_Color
        codeV.Base.textColor = UIColor.textTitleColorBlack
        codeV.callBacktext = {(str) in
            
        
            self.codeInputFinish(passwordText: str)
            
        }
        
        
        view.addSubview(codeV)

        
        intro1Lab.text = "60秒后重新获取"
        intro1Lab.textColor = UIColor.textTitleColor
        intro1Lab.font = UIFont.commonFontSmaller
        view.addSubview(intro1Lab)
        let _ = intro1Lab.sd_layout()?.leftSpaceToView(view,32)!.heightIs(20)!.topSpaceToView(introLab,100)!.rightSpaceToView(view,32)
        
        self.timeChange()
        
        

    }

    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        
    }
    @objc func bgClick(){
        
    }

    
    func codeInputFinish(passwordText:String){
        
        sleep(UInt32(0.5))
        //苹果审核专用
        if passwordText == "0000" && self.phone == "15088703801" {
            
            SPUtil.init().loginStatus = 1

            SPUtil.init().token = "1245c0f9-6019-40e8-9a65-dea9385b6b6c"
            ALNetHTTPCommonConfig.appToken = "1245c0f9-6019-40e8-9a65-dea9385b6b6c"
            SPUtil.init().leaguerId = "19120300005670140"
            SPUtil.init().mobile = "15088703801"
            SPUtil.init().headImg = "https://hqctv.oss-cn-beijing.aliyuncs.com/hqctv/MjAxOTExMjYyMzM2MTc5Nzk1Mg==.png"
            SPUtil.init().sex = "男"

            SPUtil.init().birthDay = ""
            SPUtil.init().nickName = "测试"
            if APP.backToVC != nil{
                 
                self.navigationController?.popToViewController(APP.backToVC!, animated: true)
                 
             }else{
                 
                 APP.initMainVC()
             }
            
            return
        }
        
        
        if self.type == "bindwx" {
            
            API.bindPhone(params: ["mobile":self.phone!,
                               "code":passwordText]) { (result) in
                

                  
             let login = result as! LoginResult
             SPUtil.init().token = login.appToken
             ALNetHTTPCommonConfig.appToken = login.appToken!
             SPUtil.init().leaguerId = login.userId ?? ""
             SPUtil.init().mobile = login.mobile ?? ""
             SPUtil.init().headImg = login.headImg ?? ""
                                
             if login.sex == "1"{
                 
                 SPUtil.init().sex = "男"

             }else if login.sex == "2"{
                 
                 SPUtil.init().sex = "女"
                
             }else{
                 
                 SPUtil.init().sex = ""

            }
                                
            SPUtil.init().birthDay = login.birthDay ?? ""

            SPUtil.init().nickName = login.nickName ?? ""
                                
                                
            if APP.backToVC != nil{
                 
                self.navigationController?.popToViewController(APP.backToVC!, animated: true)
                 
             }else{
                 
                 APP.initMainVC()
             }

            }
            
            return
        }
        
        API.login(params: ["mobile":self.phone!,
                           "checkCode":passwordText]) { (result) in
            
                            SPUtil.init().loginStatus = 1

                            let login = result as! LoginResult
                            SPUtil.init().token = login.appToken
                            ALNetHTTPCommonConfig.appToken = login.appToken!
                            SPUtil.init().leaguerId = login.userId ?? ""
                            SPUtil.init().mobile = login.mobile ?? ""
                            SPUtil.init().headImg = login.headImg ?? ""
                                            if login.sex == "1"{
                                                
                                                SPUtil.init().sex = "男"

                                            }else if login.sex == "2"{
                                                
                                                SPUtil.init().sex = "女"
                                            }else{
                                                
                                                SPUtil.init().sex = ""

                            }
                            SPUtil.init().birthDay = login.birthDay ?? ""
                            SPUtil.init().nickName = login.nickName ?? ""
                            if APP.backToVC != nil{
                                 
                                self.navigationController?.popToViewController(APP.backToVC!, animated: true)
                                 
                             }else{
                                 
                                 APP.initMainVC()
                             }
            
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    //倒计时
    func timeChange() {
        
        var time = 120
        let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))  //此处方法与Swift 3.0 不同
        codeTimer.setEventHandler {
            
            time = time - 1
            
            DispatchQueue.main.async {
                
            }
            
            if time < 0 {
                codeTimer.cancel()
                DispatchQueue.main.async {
                    POP(vc: self)
                    codeTimer.cancel()
                    
                }
                return
            }
            
            DispatchQueue.main.async {
                
                self.intro1Lab.text = "\(time)秒后重新获取"
            }
            
        }
        
        codeTimer.activate()
        
    }
}
